﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace WebMassage.Helpers
{
    /// <summary>
    /// Lớp cung cấp các hàm tiện ích
    /// </summary>
    public static class Utilities
    {
        #region Serialize Obj <-> XML
       
        /// <summary>
        /// Hàm chuyển đối tượng thành chuỗi xml xml
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SerializeObject(object obj)
        {
            XmlDocument doc = new XmlDocument();
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            MemoryStream stream = new MemoryStream();
            try
            {
                serializer.Serialize(stream, obj);
                stream.Position = 0;
                doc.Load(stream);
                return doc.InnerXml;
            }
            catch
            {
                throw;
            }
            finally
            {
                stream.Close();
                stream.Dispose();
            }
        }

        /// <summary>
        /// Hàm chuyển Xml thành đối tượng
        /// </summary>
        /// <param name="xmlOfAnObject"></param>
        /// <returns></returns>
        public static object DeSerializeObject(string xmlOfAnObject, Type myType)
        {
            StringReader read = new StringReader(xmlOfAnObject);
            XmlSerializer serializer = new XmlSerializer(myType);
            XmlReader reader = new XmlTextReader(read);
            try
            {
                return serializer.Deserialize(reader);
            }
            catch
            {
                return null;
            }
            finally
            {
                reader.Close();
                read.Close();
                read.Dispose();
            }
        }

        #endregion
    }
}